<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query.queryMap"
        :queryMoreJson="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clearType="clearType"
        :slipSelectRequest="slipSelectRequest"
        :listTypeInfo="listTypeInfo"
        ref="pageFilter"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            @change="timeChange"
            v-model="operateTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>

    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-excel>
          <el-button @click="exportExcel()">导出excel</el-button>
        </template>
      </NewPageFilter>
      <div class="display-flex">
        <GroupSelect
          @callback="groupSelect"
          @callbackVal="updateGroupSelections"
          :options="groupSelectInfo.options"
          v-model:selections="groupSelectInfo.selections"
        ></GroupSelect>
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <TableContainer
      v-if="groupFlag"
      class="groupFlag-container"
      :isGroupSearch="true"
      v-model:data="groupSelectInfo.data"
      :field-list="tableInfo.fieldList"
      :checkBox="false"
      :tabIndex="false"
      :pager="false"
      :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
      @exChange="exChange"
      @sortChange="sortChange"
      @handleEvent="handleEvent"
      :span-method="arraySpanMethod"
      :row-class-name="tableRowClassName"
    >
    </TableContainer>
    <!-- 表格 -->
    <TableContainer
      v-else
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :summary="true"
      :summaryFieldList="tableInfo.summaryFieldList"
      :tab-index="true"
      :check-box="false"
      v-model:query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      :all-summary="true"
      :all-summary-data="allSummaryData"
      @handleEvent="handleEvent"
      @pageInfo="pageInfo"
    >
      <template v-slot:col-orderNo="scope">
        <span
          v-if="scope.row.orderNo"
          class="slip-edit"
          @click="showDetails(scope.row)"
          >{{ scope.row.orderNo || '-' }}</span>
        <span v-else>{{ scope.row.orderNo || '-' }}</span>
      </template>
    </TableContainer>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :fieldList="tableInfo.fieldList"
      v-model:formData="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
  </div>
</template>

<script setup name="warehouseAffair">
import { exportWarehouseAffair, printWarehouseAffair } from '@/api/dataQuery.js'
import {
  getDepotAffairPage,
  getDepotAffairCustomizeGroups,
  getDepotAffairAll,
  getDepotAffairCustomizeSumAmount,
  getTargetDept,
  getTargetDepot
} from '@/api/stock.js'
import { getSupplierAll } from '@/api/core'
import { showSourceDetail } from '@/api/base'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance()
const props = defineProps(['query'])
// const $router = useRoute()
const operateTime = ref(null)
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const listTypeInfo = ref({
  supplerList: [],
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      depotAuth: {
        asTbName: 'depot_stock_affair',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
      deptAuth: {
        asTbName: 'depot_stock_affair',
        columnName: 'dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
      operateTime: {
        queryType: 'BETWEEN',
        value: null,
      },
    },
    groupMap: {},
    groups: [],
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'excel',
      type: 'slot',
    },
  ],
})

const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [],
  },
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: '总金额',
      value: 'sumStockAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
})
watch(
  () => proxy.$router,
  (route) => {
    if (
      route.currentRoute.value.name === 'warehouseAffair' &&
      route.currentRoute.value.params.query
    ) {
      let queryIn = JSON.parse(route.currentRoute.value.params.query)
      if (queryIn) {
        filterInfo.value.query.queryMap = proxy.$fn.deepClone(
          filterInfo.value.copyQueryMap
        )
        filterInfo.value.query.queryMap = {
          ...filterInfo.value.query.queryMap,
          ...queryIn.queryMap,
        }
        if (queryIn && queryIn.queryMap && queryIn.queryMap.operateTime) {
          operateTime.value = queryIn.queryMap.operateTime.value.split(',')
        }
        // proxy.$nextTick(() => {
        // search()
        getCustomize()
        // })
      }
    }
  },
  { immediate: true, deep: true }
)
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
function getSupplier() {
  let params = {
    supplierAuth: 'supplierId',
    sort: 'create_time desc',
  }
  getSupplierAll(params).then((res) => {
    if (res && res.success && res.data && res.data.length) {
      let supplerList = [
        {
          key: '-',
          value: '-2',
        },
      ]
      let data = res.data.map((item) => {
        return {
          key: item.supplierName,
          value: item.supplierId.toString(),
        }
      })
      listTypeInfo.value.supplerList = data.concat(supplerList)
    }
  })
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getDepotAffairCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getDepotAffairAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      asTbName: 'depot_stock_affair',
      columnName: 'dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
    {
      asTbName: 'depot_stock_affair',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  if ((await groupSelectInfo.value.selections.length) > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
async function getList() {
  tableInfo.value.refresh = Math.random()
  getSummary()
}
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
    setTimeout(() => {
      getSummary()
    }, 0);
  }
}
function getSummary() {
  let params = {}
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(filterInfo.value.query)
    params.queryMap = {}
  } else {
    params = filterInfo.value.query
  }
  getDepotAffairCustomizeSumAmount(params).then((res) => {
    if (res && res.success) {
      if (res.data && res.data[0] !== null) {
        allSummaryData.value.data = [{ sumStockAmount: res.data }]
      } else {
        allSummaryData.value.data = []
      }
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  operateTime.value = null
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'depotStockAffairDetailList-com.slip.spd.entity.vo.stock.DepotStockAffairVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )

      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      if (proxy.$route.params.query) {
        let queryIn = JSON.parse(proxy.$route.params.query)
        if (queryIn) {
          filterInfo.value.query.queryMap = {
            ...filterInfo.value.query.queryMap,
            ...queryIn.queryMap,
          }
          if (queryIn && queryIn.queryMap && queryIn.queryMap.operateTime) {
            operateTime.value = queryIn.queryMap.operateTime.value.split(',')
          }
        }
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        if(item.value === 'targetDepotName' || item.value === 'targetDeptName'){
          item.query = filterInfo.value.query
        }
        item.event = search
      })

      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getDepotAffairPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}
function showDetails(row){
  console.log(row)
  showSourceDetail(row.orderNo).then(res => {
    if(res && res.success){
      let data = res.data
      let url = data.url
      let name = ''
      let routes = proxy.$store.state.permission.routes
      data.businessId = row.orderId
      routes.map((item) => {
        if (item.children && item.children.length) {
          item.children.map((i) => {
            if (i.url === url) {
              name = url
            }
          })
        }
      })

      if (name) {
        proxy.$router.push(url)
        console.log(data)
        proxy.$store.dispatch('settings/toPage', data)
      } else {
        proxy.$message({
          duration: 3500,
          type: 'warning',
          showClose: true,
          message: '你没有相应的菜单权限',
        })
      }
    }
    
  })
}
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: exportWarehouseAffair, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.operateTime.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.operateTime.value = null
  }
}
function print() {
  printWarehouseAffair(
    proxy.$fn.delEmptyAttribute(filterInfo.value.query)
  ).then((resp) => {
    if (resp && resp.success) {
      proxy.$print.printOrder(resp.data)
    }
  })
}

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('warehouseAffair:price'),
    hidden: true,
    show: false,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('warehouseAffair:price'),
    hidden: true,
    show: false,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('warehouseAffair:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
  typeValue: {
    label: '类型',
    value: 'typeValue',
    asValue: 'type',
    componentType: 'select-model',
    code: 'stock_affair_type',
    show: false,
    hidden: true,
  },
  exportStoreTypeValue: {
    label: '出入库类型',
    value: 'exportStoreTypeValue',
    asValue: 'exportStoreType',
    componentType: 'select-model',
    code: 'export_store_type',
    show: false,
    hidden: true,
  },
  operateTime: {
    label: '操作时间',
    value: 'operateTime',
    componentType: 'dateTime',
    slot: true,
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    type: 'slot',
    hidden: true,
  },
  supplierName: {
    label: '供应商',
    value: 'supplierName',
    asValue: 'supplierId',
    componentType: 'select',
    list: 'supplerList',
    hidden: false,
    show: true,
    event: search,
    clearable: true,
  },
  fiscalPeriodName: {
    label: '会计期间',
    value: 'fiscalPeriodName',
    asValue: 'fiscalPeriodName',
    componentType: 'select-fiscal-period',
    query: {
      fiscalType: 1,
    }, //1 = 物资 2 = 资产
    highlightRow: true,
    checkBox: false,
    show: false,
    hidden: true,
  },
  targetDepotName: {
      label: '仓库',
      value: 'targetDepotName',
      asValue: 'targetDepotId',
      componentType: 'slip-select',
      query: {
        
      },
      api: getTargetDepot,
      show: false,
      hidden: true,
    },
    targetDeptName: {
      label: '部门',
      value: 'targetDeptName',
      asValue: 'targetDeptId',
      query: {
        
      },
      api: getTargetDept,
      componentType: 'slip-select',
      show: false,
      hidden: true,
    }
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
})
getCustomize()
getSupplier()
</script>

<style scoped></style>
